package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.common.MQConstant;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> list(@RequestParam("page") Integer pageNum, @RequestParam("size") Integer pageSize) {
        int no = (pageNum - 1) * pageSize;
        Page<Item> itemPage = new Page<>(no, pageSize);
        itemService.page(itemPage);
        return new PageDTO<>(itemPage.getTotal(), itemPage.getRecords());

    }


    /**
     * 根据id查询商品
     */
    @GetMapping("/{id}")
    Item findById(@PathVariable("id") Long id) {

        return itemService.getById(id);
    }


    //新增商品
    @PostMapping
    public void save(@RequestBody Item item) {

        itemService.save(item);
        rabbitTemplate.convertAndSend(MQConstant.MQ_EXCHANGE, MQConstant.INSERT_KEY, item.getId());
    }

    /**
     * 下架
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void putStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {

        //根据id查询该商品，将状态更改即可
        Item item = itemService.getById(id);
        item.setStatus(status);
        itemService.updateById(item);
        rabbitTemplate.convertAndSend(MQConstant.MQ_EXCHANGE, MQConstant.DELETE_KEY, item.getId());

}

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id) {
        itemService.removeById(id);
    }

    /**
     * 修改
     */
    @PutMapping
    public void putItem(@RequestBody Item item) {
        if (Objects.nonNull(item)) {
            itemService.updateById(item);
        }
    }

}
